<template>
	<div class="page-wrapper">	
		<div style="height:8%; padding-bottom:var(--mPadding);">
			<div class="flex-btn large" @click="info = { visible:true, forEdit:false } ">
				<img :src="Icon1" />
				<span>新增巡检对象</span>
			</div>
			<div class="flex-btn large opacity" @click="batchVisible = { visible:true } ">
				<img :src="Icon2" />批量操作
			</div>
			<div class="flex-btn large opacity" @click="handlePreview">
				<img :src="Icon3" />导出选中对象的巡检表
			</div>
			<div class="flex-btn large opacity" @click="handlePatchLabel">
				<img :src="Icon2" />批量设置识别标签
			</div>
		</div>
		<div style="height:92%">
			<TableWrapper :style="{ height:'100%' }" :controls="controls" :pageInfo="pageInfo" :sourceData="tableData" :column="column" :total="total"  @search="handleSearch" @selection="handleSelectRow" />
		</div>
		<!-- 新建巡检对象弹窗 -->
		<InspectionObjDrawer v-model:info="info" @refresh="fetchObjectList" />
		<!-- 下拉浮窗 -->
		<DropdownBtn ref="popRef" :currentRef="currentRef" :hasDel="true" @onSubmit="handleDelete">
			<div @click="handleLabel"><i class="ri-qr-code-line"></i>识别标签管理</div>
			<div @click="$router.push({ path:'/inspectionObject/inspectionHistory', query:{ id:currentRow.targetId, page:pageInfo.page } })"><i class="ri-file-history-line"></i>查看历史巡检结果</div>
		</DropdownBtn>
		<!-- 批量操作 -->
		<BatchSettingModal v-model:info="batchVisible" :attrList="attrList" :rows="rows" @refresh="fetchObjectList" />
		<BatchSettingLabel v-model:info="labelVisible" :rows="rows" />
	</div> 
</template>

<script setup>
	import { reactive, onMounted, watch, ref, h, nextTick } from 'vue';
	import { useRouter, useRoute } from 'vue-router';
	import { getTplList, getLabelList } from '@/api/tpl.js';
	import { getObjectList, delObject } from '@/api/object.js';
	import { getFieldAttrs, getAttrMachList  } from '@/api/cycle.js';
    import { getGroupList } from '@/api/group.js';
	import { Search, View, RefreshRight, InfoFilled, Delete, EditPen, Plus, Printer } from '@element-plus/icons-vue'
	import { ElMessage, ElPopconfirm, ElInput  } from 'element-plus';
	import TableWrapper from '@/components/TableWrapper/index.vue';
	import InspectionObjDrawer from './InspectionObjDrawer.vue';
	import DropdownBtn from '@/components/DropdownBtn.vue';
	import BatchSettingModal from './BatchSettingModal.vue';
	import BatchSettingLabel from './BatchSettingLabel.vue';
	import { downloadExcel } from '@/utils/excel.js';
	import { setStorage } from '@/utils/encryption.ts';
	import Icon1 from '@/assets/icon-add.png';
	import Icon2 from '@/assets/icon-patch.png';
	import Icon3 from '@/assets/icon-export.png';
	
	const router = useRouter();
	const route = useRoute();
	const tableData = ref([]);
	const total = ref(0);
	const tplList = ref([]);
	const tplTotal = ref(0);
	const attrList = ref([]);
	const labelList = ref([]);
	const groupList = ref([]);
	const groupTotal = ref(0);
	const popRef = ref();
	const pageInfo = reactive({ page:1, pageSize:10 });
	const currentRow = ref({});
	let refArr = [];
	const currentRef = ref();
	const rows = ref([]);
	const labelVisible = ref({ visible:false });
	const controls = ref([
		{ type:'input', paramKey:'targetName', placeholder:'输入名称查询' },
		{ type:'select', paramKey:'templateCode', payload:[], placeholder:'请选择模板' },
		{ type:'treeselect', paramKey:'attrId', fieldMaps:{ label:'attrName', value:'attrId', children:'subEnergyFieldAttr' }, payload:[], placeholder:'请选择位置' },
		{ type:'select', paramKey:'groupId', payload:[], placeholder:'请选择分组' }
	]);
	const info = ref({ visible:false, forEdit:false });
	const batchVisible = ref({ visible:false });
	const comMaps = {};
    const column = [
		{ hasSelection:true },
		{ label:'序号', width:'5%', hasTpl:true, render:(row, index)=>{
			const val = ( pageInfo.page - 1 ) * pageInfo.pageSize + index + 1;
			return { com:h('div', null, val )};
		}},
        { label:'巡检对象模板', width:'10%', prop:'templateName' }, 
        { label:'名称', width:'14%', prop:'targetName' },
		{ label:'标签', width:'6%', prop:'labelName', hasTpl:true, render:row=>{
			let obj = labelList.value.filter(i=>i.labelId === row.labelId)[0] || {};
			return { com:h('div', null, obj.labelName || '--') }
		}},
		{ label:'位置', width:'14%', prop:'attrName'},
		{ label:'分组', width:'10%', hasTpl:true, render:row=>({ com:h('div', null, row.groupName || '--' ) })},
		{ label:'是否需要扫码开始巡检', width:'10%', hasTpl:true, render:row=>({ com:h('div', null, Number(row.needScan) === 1 ? '是' : '否' ) })},
        { label:'操作', width:'16%', hasTpl:true, isAction:true, render:(row, index)=>{
			if ( index < 0 ) return;
			return {
				com:h('div', { class:'action-container' }, [
            	    h('div', { onClick:()=>{ router.push({ path:'/inspectionObject/inspectionItems', query:{ id:row.targetId, page:pageInfo.page } }) }}, [h('i', { class:'ri-settings-line' }), h('span', null, '巡检项管理')]),
            	    h('div', { onClick:()=>{ info.value = { visible:true, forEdit:true, row } }}, [h('i', { class:'ri-edit-line' }), h('span', null, '编辑')]),
					h('div', { ref:(el)=>{ refArr.push(el) }, onClick:()=>{ currentRef.value = refArr[index]; currentRow.value = row; nextTick(()=>popRef.value.handleOpen(row.targetId) ) }  }, [h('span', null, '更多' ), h('i', { class:'ri-arrow-down-s-line' }) ] )
            	])
			}
        }
        }
    ]; 	
	function handleSelectRow(arr){
		rows.value = arr;
	}
	
	function handleDelete(targetId){
		delObject({ targetId })
		.then(res=>{
			if ( res.data.code === 200 ) {
				ElMessage({
					type:'success',
					message:'删除巡检对象成功'
				});
				fetchObjectList();
			}
		})
	}
	function handleLabel(){
		setStorage('currentRow', JSON.stringify(currentRow.value));
		router.push({ path:'/inspectionObject/labelManage', query:{ page:pageInfo.page } });
	}

	watch([tplList, attrList, groupList], ()=>{
		controls.value[1] = { type:'select', paramKey:'templateCode', payload:tplList.value, total:tplTotal.value, hasPagination:true, search:fetchTplList, placeholder:'请选择模板', labelKey:'templateCode', labelName:'templateName'  };
		controls.value[2] = { type:'treeselect', paramKey:'attrId', fieldMaps:{ label:'attrName', value:'attrId', children:'subEnergyFieldAttr' },  payload:attrList.value, placeholder:'请选择位置' };
		controls.value[3] = { type:'select', paramKey:'groupId', extraOption:{ label:'未分组', key:'-1' }, payload:groupList.value, total:groupTotal.value, hasPagination:true, placeholder:'请选择分组', labelKey:'groupId', labelName:'groupName' };
	})
	function handlePreview(){
		if ( rows.value.length ) {
			router.push({ path:'/inspectionObject/exportHistory', query:{ ids:JSON.stringify(rows.value.map(i=>({ i:i.targetId, n:i.targetName }) ))  }})
		} else {
			ElMessage({
                type:'info',
                message:'请勾选要导出的巡检对象'
            })
		}
	}
	function handlePatchLabel(){
		if ( rows.value.length ) {
			labelVisible.value = { visible:true };
		} else {
			ElMessage({
                type:'info',
                message:'请勾选要设置标签的巡检对象'
            })
		}
	}
	// 请求模板
	const fetchTplList = (params)=>{
		// 实际的axios请求;
		params = params || { page:1, pageSize:10 };
		getTplList(params)
		.then(res=>{
			if ( res.data.code === 200 ){
				tplList.value = res.data.data;
				tplTotal.value = res.data.total;
			}
		})
	};	
	// 请求维度属性
	const fetchFieldAttrs = ()=>{     
        getFieldAttrs()
        .then(res=>{
            if ( res.data.code === 200 ){
                attrList.value = res.data.data;          
            }
        })                                 
    }
	// 请求分组
	const fetchGroupList = (params)=>{
		// 实际的axios请求;
		params = params || { page:1, pageSize:10 };
		getGroupList(params)
		.then(res=>{
			if ( res.data.code === 200 ){
				groupList.value = res.data.data;
				groupTotal.value = res.data.total;
			}
		})
	}
	const handleSearch = (optional, pageInfo)=>{
		// 调用请求接口
		parentPageInfo.value = { ...pageInfo };
		fetchObjectList({ ...optional, ...pageInfo });
	}
	
	const fetchLabelList = ()=>{
        getLabelList()
        .then(res=>{
            if ( res.data.code === 200 ) {
                labelList.value = res.data.data;
            }
        })
    }
	const fetchObjectList = (params)=>{
		// 实际的axios请求;
		refArr = [];
		params = params || {} ;
		let realParams = { page:pageInfo.page, pageSize:pageInfo.pageSize };
		Object.keys(params).forEach(key=>{
			if ( params[key] ) {
				realParams[key] = params[key];
			}
		})
		getObjectList(realParams)
		.then(res=>{
			if ( res.data.code === 200 ){
				tableData.value = res.data.data;
				total.value = res.data.total;
			}
		})
	};
	onMounted(()=>{
		if ( route.query.page ) {
			pageInfo.page = Number(route.query.page);
		} 
		fetchObjectList();
		fetchTplList();
		fetchFieldAttrs();
		fetchGroupList();
		fetchLabelList();
	})
	
</script>
